package com.jsy.mqhelper.charlotterpc.protocol;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;

/**
 * @author: SongyangJi
 * @description:
 * @since: 2021/9/25
 */

@ToString
@NoArgsConstructor
public class CharlotteRpcResponse {
    //    String jsonRpcVersion;
    //    String id;

    /**
     * 方法的执行结果
     */
    @JsonIgnore
    private Object result;
    /**
     * result的包装
     */
    @Getter
    @Setter
    private ObjectWrapper resultWrapper;

    /**
     * 抛出的异常
     */
    @JsonIgnore
    private Throwable exception;
    /**
     * exception的包装
     */
    @Getter
    @Setter
    private ObjectWrapper exceptionWrapper;

    @Getter
    @Setter
    private Error error;

    public CharlotteRpcResponse(Object result, Throwable exception, Error error) {
        this.resultWrapper = ObjectWrapper.wrap(result);
        this.exceptionWrapper = ObjectWrapper.wrap(exception);
        this.error = error;
    }

    public CharlotteRpcResponse(Object result) {
        this.resultWrapper = ObjectWrapper.wrap(result);
    }

    public CharlotteRpcResponse(Throwable exception) {
        this.exceptionWrapper = ObjectWrapper.wrap(exception);
    }

    public CharlotteRpcResponse(Error error) {
        this.error = error;
    }


    @JsonIgnore
    public Object getResult() {
        if (resultWrapper == null) return null;
        return result != null ? result : (result = resultWrapper.unwrap());
    }

    @JsonIgnore
    public Throwable getException() {
        if (exceptionWrapper == null) return null;
        return exception != null ? exception : (exception = (Throwable) exceptionWrapper.unwrap());
    }


    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Error {
        ResponseCode code;

        String message;

        String data;

        public Error(ResponseCode code, String message) {
            this.code = code;
            this.message = message;
        }
    }

}

